import { login, getUserInfo } from '@/api/user'
import { setToken, getToken, removeToken } from '@/utils/auth'
import { constantRoutes, resetRouter } from '@/router'

const state = {
  token: getToken(), // 初始化token
  userInfo: {},
  routes: constantRoutes // 初始化静态路由
}

const mutations = {
  // 将动态路由信息存入router中
  setAsyncRouters(state, asyncRouters) {
    // 这里千万不要用push，否则在不刷新页面的情况下退出重登回出现问题
    state.routes = [...constantRoutes, ...asyncRouters]
  },

  setToken(state, token) {
    state.token = token
    // 持久化token
    setToken(token)
  },

  removeToken(state) {
    state.token = null
    removeToken()
  },

  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  }

}

const actions = {
  async login(context, data) {
    // 发请求获取token，存入state
    const token = await login(data)
    context.commit('setToken', token)
  },

  logout(context) {
    context.commit('removeToken')
    context.commit('setUserInfo', null)
    // 重置路由
    resetRouter()
  },

  async aquireUserInfo(context) {
    // 发送请求获取用户信息，存入state
    const userInfo = await getUserInfo()
    context.commit('setUserInfo', userInfo)
    return userInfo
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
